<template>
    <div>
        <page-header :title="$route.meta.title" />
        <page-main>
            <el-button-group>
                <el-button type="primary" icon="el-icon-circle-plus-outline" :disabled="loading" size="mini" @click="add">添加</el-button>
                <el-button type="primary" icon="el-icon-edit" :disabled="!currentId" size="mini" @click="edit">编辑</el-button>
                <el-button type="primary" icon="el-icon-delete" :disabled="!currentId" size="mini" @click="del">删除</el-button>
                <el-button type="primary" icon="el-icon-circle-close-outline" :disabled="!currentId" size="mini" @click="cancel">取消</el-button>
            </el-button-group>
            <el-row>
                <el-col :span="7" style="margin-top: 15px;">
                    <div v-loading="listLoading" style="padding: 0 15px;">
                        <el-tree ref="tree" class="filter-tree" node-key="id" default-expand-all highlight-current :expand-on-click-node="false" :data="dataList" :props="defaultProps" @node-click="getMenuData" />
                    </div>
                </el-col>
                <el-col :span="17" style="margin-top: 15px;">
                    <el-card shadow="always">
                        <el-form ref="form" label-position="right" label-width="180px" :model="form" :rules="rules" size="small" :disabled="!formEdit">
                            <el-form-item label="父级节点" prop="pid">
                                <el-input v-model="form.pid" :disabled="true" placeholder="父级节点" />
                            </el-form-item>
                            <el-form-item label="标题" prop="title">
                                <el-input v-model="form.title" placeholder="请输入标题" />
                            </el-form-item>
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" placeholder="请输入备注" />
                            </el-form-item>
                            <el-form-item label="权限" prop="remark">
                                <div v-loading="menuLoading">
                                    <el-table :data="menuList" border stripe highlight-current-row style="line-height: normal;">
                                        <el-table-column prop="modules_name" width="200" label="模块" />
                                        <el-table-column label="权限">
                                            <template slot-scope="scope">
                                                <el-row type="flex" align="middle">
                                                    <el-col>
                                                        <el-checkbox-group v-model="form.purviews">
                                                            <!-- <el-checkbox v-for="auth in scope.row.childs" :key="`${scope.row.modules_name}.${auth.auth_name}`" :label="`${scope.row.modules_name}.${auth.auth_name}`">{{ auth.auth_name }}</el-checkbox> -->
                                                            <el-checkbox v-for="auth in scope.row.childs" :key="`${scope.row.modules_name}.${auth.auth_name}`" :label="auth.id">{{ auth.title }}</el-checkbox>
                                                        </el-checkbox-group>
                                                    </el-col>
                                                    <el-col style="flex: 1; margin-left: 20px;">
                                                        <el-checkbox v-model="checkAll[scope.$index].checkAll" border size="small" :indeterminate="checkAll[scope.$index].indeterminate" @change="handleCheckAll($event, scope.$index)">全选</el-checkbox>
                                                    </el-col>
                                                </el-row>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </el-form-item>
                            <el-form-item label="状态">
                                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
                            </el-form-item>
                            <el-form-item v-if="formEdit">
                                <el-button type="primary" :loading="submitLoading" @click="submit">提交</el-button>
                                <el-button @click="reset">清空</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                </el-col>
            </el-row>
        </page-main>
    </div>
</template>

<script>
const form = {
    id: '',
    pid: 0,
    title: '',
    identifier: '',
    remark: '',
    purviews: [],
    status: 1
}
export default {
    data() {
        return {
            loading: false,
            formEdit: false,
            listLoading: true,
            menuLoading: true,
            submitLoading: false,
            currentId: 0,
            dataList: [],
            menuList: [],
            defaultProps: {
                label: 'title'
            },
            form: JSON.parse(JSON.stringify(form)),
            rules: {
                title: { required: true, message: '请完善内容', trigger: 'blur' },
                remark: { required: true, message: '请完善内容', trigger: 'blur' },
                purviews: [
                    { validator: (rule, value, callback) => {
                        if (value.length == 0) {
                            callback(new Error('至少选择一个权限'))
                        } else {
                            callback()
                        }
                    }, trigger: 'change' }
                ]
            }
        }
    },
    computed: {
        // 用于全选按钮
        checkAll() {
            let isCheckAll = []
            this.menuList.forEach(module => {
                let arr = []
                module.childs.forEach(auth => {
                    if (this.form.purviews.includes(auth.id)) {
                        arr.push(auth.id)
                    }
                })
                isCheckAll.push({
                    checkAll: arr.length == module.childs.length,
                    indeterminate: arr.length > 0 && arr.length < module.childs.length
                })
            })
            return isCheckAll
        }
    },
    created() {
        this.init()
        this.getMenuList()
    },
    methods: {
        async init() {
            this.listLoading = true
            const menu = await this.$api.post('/system/role/tabulation')
            this.dataList = menu.data.data
            this.fixMenuData(this.dataList)
            this.listLoading = false
        },
        async getMenuList() {
            this.menuLoading = true
            const menu = await this.$api.post('system/auth/tabulation')
            this.menuList = menu.data.data
            console.log(menu.data)
            this.menuLoading = false
        },
        fixMenuData(menus) {
            menus.forEach(element => {
                element.title = element.title || element.meta.title || ''
                if (element.children) {
                    this.fixMenuData(element.children)
                }
            })
        },
        getMenuData(data) {
            const { id, pid, title, remark, purviews, status } = data
            this.form = {
                id,
                pid,
                title,
                remark,
                purviews,
                status
            }
            this.currentId = id
        },
        submit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submitLoading = true
                    const params = {
                        pid: this.currentId,
                        ...this.form
                    }
                    // 编辑
                    if (params.id) {
                        this.$api
                            .post('system/role/update', params)
                            .then(() => {
                                this.$message.success('保存成功')
                                this.init()
                                this.submitLoading = false
                                this.formEdit = false
                            })
                            .catch(() => {
                                this.submitLoading = false
                            })
                    } else {
                        // 新增
                        // delete params.id
                        this.$api
                            .post('system/role/create', params)
                            .then(() => {
                                this.$message.success('添加成功')
                                // this.reset()
                                this.init()
                                this.submitLoading = false
                                this.formEdit = false
                            })
                            .catch(() => {
                                this.submitLoading = false
                            })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        handleCheckAll(flag, index) {
            if (!this.menuList.length) return
            if (flag) {
                this.menuList[index].childs.forEach(auth => {
                    if (!this.form.purviews.includes(auth.id)) {
                        this.form.purviews.push(auth.id)
                    }
                })
            } else {
                this.menuList[index].childs.forEach(auth => {
                    this.form.purviews = this.form.purviews.filter(item => item != auth.id)
                })
            }
        },
        del() {
            this.$confirm('确认删除该菜单？', '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '删除',
                cancelButtonText: '取消'
            }).then(() => {
                this.$api.post('system/role/delete', { id: this.currentId }).then(() => {
                    this.$message.success('操作成功')
                    this.currentId = 0
                    this.reset()
                    this.init()
                })
            })
        },
        add() {
            this.reset()
            this.form.pid = this.currentId
            this.formEdit = true
        },
        edit() {
            this.formEdit = true
        },
        cancel() {
            this.formEdit = false
            this.currentId = 0
            this.reset()
        },
        reset() {
            this.form = JSON.parse(JSON.stringify(form))
            // this.$refs.menuTree.setCheckedKeys([])
        },
        handleCheckChange() {
            this.getCheckedKeys()
        },
        getCheckedKeys() {
            // this.form.purviews = this.$refs.menuTree.getCheckedKeys()
        }
    }
}
</script>
